<template>
  <div>
      <!-- Header -->
      <div style="height: 60px; border-bottom:2px; display: flex;align-items: center;">
          <div style="width: 240px;height: 60px; display: flex;align-items: center;padding-left: 20px; background-color: #96ccff">
            <img class="rotating-logo" style="width:30px;height: auto;margin-left: 20px" src="../assets/imgs/logo.png" height="200" width="200" alt=""/>
            <span style="font-size: 20px;font-weight: bold;color: #2c82ff;margin-left: 15px">校友帮</span>
          </div>

          <div style="flex:1;margin-left: 10px" >
              <div style="font-weight: bold;font-size: 20px">
                  {{ breadcrumb }}
              </div>

          </div>


          <el-dropdown @command="handleCommand">
                <div class="el-dropdown-link" style="width: fit-content;display: flex;align-items: center;">
                  <img 
                    style="width: 40px;border-radius: 100%" 
                    :src="userInfo.avatar"
                    @error="handleAvatarError"
                  />
                  <span style="margin: 5px">{{ userInfo.name }}</span>
                </div>
              <template #dropdown>
                  <el-dropdown-menu>
                      <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                      <el-dropdown-item command="settings">设置</el-dropdown-item>
                      <el-dropdown-item command="help">帮助</el-dropdown-item>
                      <el-dropdown-item command="logout">退出</el-dropdown-item>
                  </el-dropdown-menu>
              </template>
          </el-dropdown>

      </div>
      <!-- Header Over -->

      <!-- 个人信息弹窗 -->
      <el-dialog v-model="profileDialogVisible" title="个人信息" width="500px">
        <el-form :model="profileForm" label-width="100px">
          <!-- 头像上传 -->
          <el-form-item label="头像">
            <el-upload
              class="avatar-uploader"
              action="http://localhost:8848/files/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          
          <!-- 其他个人信息 -->
          <el-form-item label="用户名">
            <el-input v-model="profileForm.name" />
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="profileForm.username" disabled />
          </el-form-item>
          <el-form-item label="密码">
            <div style="display: flex; gap: 80px;">
              <el-input v-model="profileForm.password" type="password" show-password :disabled="!isPasswordVerified" />
              <el-button v-if="!isPasswordVerified" type="primary" @click="verifyPassword">验证密码</el-button>
              <el-button v-else type="success" @click="resetPasswordVerification">重置验证</el-button>
            </div>
          </el-form-item>
          <el-form-item label="电话">
            <el-input v-model="profileForm.phone" />
          </el-form-item>
          <el-form-item label="邮箱">
            <el-input v-model="profileForm.email" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="profileDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="saveProfile">保存</el-button>
          </span>
        </template>
      </el-dialog>

      <!-- 下方区域：Aside   &    Main -->
      <div style="display: flex; height: calc(100vh - 60px);">
          <!-- Aside -->
          <div style="width: 240px; height: 100%; overflow-y: auto;">
              <!-- default-active:默认打开一级or二级    default-opendeds：默认展开某一级菜单 -->
              <el-menu router default-active="router.currentRoute.value.path" :default-openeds="['2', '3']" style="height: 100%;">

                  <el-menu-item index="/manager/home">
                      <el-icon><Menu /></el-icon>
                      <span>首页</span>
                  </el-menu-item>

                  <el-sub-menu index="4">
                      <template #title>
                          <el-icon><Service /></el-icon>
                          <span>校园互助</span>
                      </template>
                      <el-menu-item index="/manager/task-publish">
                          <span>发布任务</span>
                      </el-menu-item>
                      <el-menu-item index="/manager/task-list">
                          <span>浏览接单</span>
                      </el-menu-item>
                  </el-sub-menu>
                  <el-sub-menu index="1" v-if="userInfo.role === 'ADMIN'">
                      <template #title>
                          <el-icon><Bell /></el-icon>
                          <span>数据管理</span>
                      </template>
                      <el-menu-item index="/manager/notice">
                          <span>公告列表</span>
                      </el-menu-item>
                  </el-sub-menu>

                  <el-sub-menu index="2" v-if="userInfo.role === 'ADMIN'">
                      <template #title>
                          <el-icon><User /></el-icon>
                          <span>用户管理</span>
                      </template>
                      <el-menu-item index="/manager/admin">
                          <span>管理员信息</span>
                      </el-menu-item>
                      <el-menu-item index="/manager/user">
                          <span>普通用户信息</span>
                      </el-menu-item>
                  </el-sub-menu>
                  
                  <el-sub-menu index="3">
                      <template #title>
                          <el-icon><ChatDotRound /></el-icon>
                          <span>智能助手</span>
                      </template>
                      <el-menu-item index="/manager/ai-chat">
                          <span>AI问答</span>
                      </el-menu-item>
                  </el-sub-menu>

              </el-menu>
          </div>
          <!-- Aside Over -->

          <!-- Main -->
          <div style="flex: 1; width: 0; padding: 10px; background-color: #f2f4ff; overflow-y: auto;">
              <RouterView />
          </div>
          <!-- Main Over -->
      </div>
  </div>
</template>

<script setup>

import { ElMessage, ElMessageBox } from 'element-plus';
import {computed, ref, reactive} from 'vue';
import { useRoute } from 'vue-router';
import request from "@/utils/request.js";

const route = useRoute();

// 获取用户信息
const userInfo = computed(() => {
  const info = JSON.parse(localStorage.getItem('userInfo') || '{}');
  return {
    name: info.name || 'Name',
    avatar: info.avatar || 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png',
    role:info.role
  };
});

// 菜单配置
const menuConfig = {
  '/manager/home': { title: '首页' },
  '/manager/notice': { title: '公告列表', parent: '数据管理' },
  '/manager/admin': { title: '管理员信息', parent: '用户管理' },
  '/manager/user': { title: '用户信息', parent: '用户管理' },
  '/manager/ai-chat': { title: 'AI问答', parent: '智能助手' },
  '/manager/task-publish': { title: '发布任务', parent: '校园互助' },
  '/manager/task-list': { title: '浏览接单', parent: '校园互助' }
};

// 计算面包屑
const breadcrumb = computed(() => {
  const currentPath = route.path;
  const currentMenu = menuConfig[currentPath];
  
  if (!currentMenu) {
    return '首页';
  }
  
  if (currentMenu.parent) {
    return `首页 / ${currentMenu.parent} / ${currentMenu.title}`;
  } else {
    return currentMenu.title;
  }
});

const logout = () => {
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')  // 清除token
    location.href = '/login'
}

// 处理下拉菜单命令
const handleCommand = async (command) => {
  if (command === 'logout') {
    logout();
  } else if (command === 'profile') {
    // 打开个人信息弹窗
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    Object.assign(profileForm, userInfo);
    profileDialogVisible.value = true;
  } else if (command === 'settings') {
    ElMessage.info('设置功能开发中');
  } else if (command === 'help') {
    ElMessage.info('帮助功能开发中');
  }
};

// 个人信息相关
const profileDialogVisible = ref(false);
const profileForm = reactive({
    id: '',
    username: '',
    name: '',
    password: '',
    phone: '',
    email: '',
    role: '',
    avatar: ''
});

// 头像上传相关方法
const handleAvatarSuccess = (res) => {
  if (res.code === '200') {
    profileForm.avatar = res.data;
    ElMessage.success('头像上传成功');
  } else {
    ElMessage.error('头像上传失败');
  }
};
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isJPG) {
    ElMessage.error('上传头像图片只能是 JPG/PNG 格式!');
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
  }
  return isJPG && isLt2M;
};
// 处理头像加载失败
const handleAvatarError = (e) => {
    e.target.src = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
}
// 保存个人信息
const saveProfile = () => {
  request.put('/admin/update', profileForm).then(res => {
    if (res.code === '200') {
      ElMessage.success('个人信息更新成功');
      // 更新本地存储的用户信息
      localStorage.setItem('userInfo', JSON.stringify(profileForm));
      profileDialogVisible.value = false;
    } else {
      ElMessage.error(res.msg || '更新失败');
    }
  });
};

const isPasswordVerified = ref(false);
const verifyPassword = () => {
  ElMessageBox.prompt('请输入当前密码进行验证，验证后可查看&修改', '验证密码', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputType: 'password',
    inputPattern: /\S+/,
    inputErrorMessage: '密码不能为空'
  }).then(({ value }) => {
    if (value === profileForm.password) {
      isPasswordVerified.value = true;
      ElMessage.success('密码验证成功');
    } else {
      ElMessage.error('密码验证失败');
    }
  }).catch(() => {
    ElMessage.info('取消验证');
  });
};

const resetPasswordVerification = () => {
  isPasswordVerified.value = false;
  ElMessage.info('已重置密码验证');
};

</script>

<style>
.el-menu{
    background-color: #96ccff;
    border-color: #96ccff;
}
.el-dropdown {
    cursor: pointer;
}
.el-tooltip__trigger {
    outline: none;
}

@keyframes rotate {
    from {
        transform: rotate(0deg);
    }
    to {
        transform: rotate(360deg);
    }
}

.rotating-logo {
    animation: rotate 3s linear infinite;
}

.avatar-uploader {
  text-align: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  text-align: center;
  line-height: 100px;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
  object-fit: cover;
}
</style>